package com.xiaobai.ThreadReentrantLock;

import com.xiaobai.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/*
线程打断ReentrantLock
 */
@Slf4j
public class LockInterrupt {
    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                //可以防止死锁 可以防止无限制的等待
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                log.debug("线程被打断，停止等待");
                throw new RuntimeException(e);
            }
            try {
                log.debug("获取锁");
            } finally {
                lock.unlock();
            }
        },"t1");
        lock.lock();
        try {
            log.debug("获取锁");
            thread.start();
            ThreadUtil.sleep(1);
            thread.interrupt();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }
    }
}
